package com.weasel.weixin.commons.session.dao;

import com.weasel.weixin.commons.session.WeixinSession;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by Dylan on 2015/12/8.
 */
public class MemorySessionDAO extends AbstractSessionDAO{

    private final static Logger logger = LoggerFactory.getLogger(MemorySessionDAO.class);

    private ConcurrentMap<String,WeixinSession> sessions = new ConcurrentHashMap<>();

    @Override
    public WeixinSession get(String sessionid) {
        if(logger.isDebugEnabled()){
            logger.debug("get session with id [{}]",sessionid);
        }
        return sessions.get(sessionid);
    }

    @Override
    public Collection<WeixinSession> list() {
        Collection<WeixinSession> values = sessions.values();
        if(null == values || values.isEmpty()){
            return Collections.EMPTY_SET;
        }else{
            return Collections.unmodifiableCollection(values);
        }
    }

    @Override
    protected void doCreate(WeixinSession session) {
        if(logger.isDebugEnabled()){
            logger.debug("dao create session");
        }
        storeSession(session);
    }

    @Override
    public boolean delete(String sessionid) {
        if(logger.isDebugEnabled()){
            logger.debug("dao delete session with id [{}]",sessionid);
        }
        WeixinSession session = sessions.remove(sessionid);
        return null != session;
    }

    @Override
    public boolean update(WeixinSession session) {
        if(logger.isDebugEnabled()){
            logger.debug("dao update session");
        }
        WeixinSession storeSession = storeSession(session);
        return null != storeSession;
    }

    protected WeixinSession storeSession(WeixinSession session){
        if(null == session){
            throw new NullPointerException("session store can not be null");
        }
        if(StringUtils.isEmpty(session.getId())){
            throw new NullPointerException("session id can not be empty");
        }
        return sessions.putIfAbsent(session.getId(),session);
    }
}
